/**
 * Created by tanbingqin on 2020/6/30.
 */
import React, { Component, PropTypes } from "react";
import { messages, eventTrack } from 'share/common'
import { connect } from 'react-redux';
import menuRoute from 'routes/menuRoute'
import SlideDocument from 'components/template/slide-document/slide-document'
import requestService from 'containers/request/request.service'
import baseService from 'share/base.service'
import errorMessage from 'share/errorMessage';
import 'styles/request/new-card-request.scss'
import BottomBlockEdit from "./bar/bottom-block-edit";
import { Tabs } from 'antd'
const TabPane = Tabs.TabPane;
import ItineraryBlock from 'containers/request/slide/content/itinerary'
import Condition from 'components/condition';
const If = Condition.If;
import SlideFrame from "components/slide-frame";
import RequestEditContent from 'containers/request/slide/content/request-edit-content'
import ApproveHistory from 'components/template/approve-history'
import BudgetExplain from 'components/template/budget-explain/budget-explain'
import ApplicationHeader from 'containers/request/slide/content/application-header'
import requestUtil from 'containers/request/slide/request-util'

class RequestEdit extends Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      form: {},
      info: {},
      adminApprove: false, //是否是流程监控平台跳转过来的
      isShowCredit: false, //是否展示信用，读取后台配置，从流程监控，费用查看跳转过来的不受此配置限制
      budgetExplainNumber: 0, //预算执行情况列表数量
      thirdPartyInfo: {}, //第三方返回信息
      creditScore: {}, //信用相关数据
      jobInfo: {}, //岗位信息
      applicant: {}, //申请人信息
      activeTab: 'itinerary', //默认tab
      quotaObj: {
        takeQuota: false, //是否申请额度
        quotaAmount: 0, //额度金额
        quotaCurrencyCode: 'CNY', //额度币种
        quotaBankCardOID: '' //额度银行卡id
      }, //申请额度相关的字段
    }
  }

  componentDidMount() {
    this.getInfo();
  }

  getInfo = () => {
    const { formOID, applicationOID } = this.props.params;
    this.setState({loading: true});
    Promise.all([
      requestService.getFormType(formOID),
      requestService.getRequestDetail(applicationOID),
      requestService.getUserCreditConfig()
    ]).then(res => {
      requestUtil.disableCompany(res[1].data);
      this.setState({
        form: res[0].data,
        info: res[1].data,
        isShowCredit: res[2] && res[2].data && res[2].data.show
      }, () => {
        this.getOtherInfo();
        this.initQuotaObj();
      });
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });
  };

  //初始化申请额度相关信息
  initQuotaObj = (isNeedCloseLoading) => {
    const { info } = this.state;
    let { quotaObj } = this.state;
    quotaObj.takeQuota = info.takeQuota;
    quotaObj.quotaAmount = info.quotaAmount;
    quotaObj.label = info.quotaBankCardDTO ? `${info.quotaBankCardDTO.paymentRemark === '002' ? messages('request-1.key15')/*瑞贝卡*/ : messages('request-1.key16')/*领创A卡*/}(${info.quotaBankCardDTO.bankAccountNo && info.quotaBankCardDTO.bankAccountNo.substr(-4)})` : '';
    quotaObj.quotaBankCardOID = info.quotaBankCardOID;
    quotaObj.quotaBankCardDTO = info.quotaBankCardDTO;
    this.setState({quotaObj});
    if (isNeedCloseLoading) {
      this.setState({loading: false});
    }
  };

  //更新单据信息
  refreshInfo = () => {
    const { applicationOID } = this.props.params;
    this.setState({loading: true});
    Promise.all([
      requestService.getRequestDetail(applicationOID),
      requestService.getBudgetExplain({
        applicationOID: applicationOID,
        mark: false //传false时后台会去查配置来看是否有查看预算执行结果的权限
      })
    ]).then(res => {
      requestUtil.disableCompany(res[0].data);
      this.setState({
        info: res[0].data,
        budgetExplainNumber: Number(res[1].data || 0)
      }, () => {
        this.initQuotaObj(true);
      });
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });
  };

  //处理其余信息：岗位，信用，预算调用等等
  getOtherInfo = () => {
    const { info, isShowCredit } = this.state;
    const { profile, loginUser } = this.props;
    Promise.all([
      requestService.getBudgetExplain({
        applicationOID: info.applicationOID,
        mark: false //传false时后台会去查配置来看是否有查看预算执行结果的权限
      }),
      loginUser.userOID !== info.applicantOID && baseService.changeLoginInfo(info.applicantOID),//代提逻辑
      isShowCredit && requestService.getUserCredit(info.applicant.userOID, info.jobId),
      baseService.getJobInfo(info.jobId),
      baseService.getUserInfo(info.applicantOID)
    ]).then(res => {
      this.setState({
        loading: false,
        budgetExplainNumber: Number(res[0].data || 0),
        creditScore: res[2] ? res[2].data || {} : {},
        jobInfo: res[3].data || {},
        applicant: res[4].data
      }, this.getThirdPartyInfo);
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });
  };

  //处理第三方返回信息
  getThirdPartyInfo = () => {
    const { info } = this.state;
    const { profile } = this.props;
    if (profile['request.external.info.display']) {
      requestService.getThirdPartyInfo(info.applicationOID).then(res => {
        this.setState({thirdPartyInfo: res.data});
      }).catch(err => {
        errorMessage(err.response);
      });
    }
  };

  refreshQuotaObj = (value) => {
    this.setState({quotaObj: value});
  };

  getChildContext() {
    const { form, info, creditScore, jobInfo, applicant, thirdPartyInfo, refreshQuotaObj } = this.state;
    return {
      applicant,
      creditScore,
      form,
      info,
      jobInfo,
      close: (isNeedRefreshList) => this.goBack(isNeedRefreshList),
      refreshInfo: () => this.refreshInfo(),
      thirdPartyInfo,
      refreshQuotaObj: value => this.refreshQuotaObj(value),
    }
  }

  goBack = (isNeedRefreshList) => {
    const { _isSlideFrame, close } = this.props;
    const { isPreVersion } = _isSlideFrame ? this.props.params : this.props.location.query;
    const { backType, pageFrom, tab } = this.props.params;
    if (isPreVersion) {
      this.context.router.push(menuRoute.getRouteItem('request').url);
      return;
    }
    if (backType === 'history') {
      window.history.go(-1);
    } else {
      if (close) {
        close(isNeedRefreshList);
      } else {
        //老逻辑的页面跳转只有my和closeList两种情况
        pageFrom && pageFrom === 'my' && this.context.router.push(menuRoute.getRouteItem('expense-report').url);
        pageFrom && pageFrom === 'closeList' && this.context.router.push(menuRoute.getRouteItem('request-close').url);
        //老逻辑且没有pageFrom，则跳到申请单列表，ps：流程监控平台没用这个goBack方法，是另外处理的
        !pageFrom && this.context.router.push(menuRoute.getRouteItem('request').url);
      }
    }
  };

  onClickEditFields = () => {
    eventTrack({
      category: '申请单编辑',
      action: '编辑单据'
    });
    const { form, info, jobInfo, quotaObj } = this.state;
    SlideFrame.open({
      title: messages('request-1.key427')/*编辑申请单*/,
      content: RequestEditContent,
      params: {
        info,
        jobInfo,
        formInfo: form,
        formOID: info.formOID,
        applicationOID: info.applicationOID,
        quotaObj
      },
      afterClose: () => {
        if (sessionStorage.getItem('isNeedApplicationRefresh') === 'true') {
          this.getInfo();
          sessionStorage.setItem('isNeedApplicationRefresh', '');
        }
      }
    }, this);
  };

  render() {
    const { loading, activeTab, info, budgetExplainNumber, quotaObj } = this.state;
    const { _isSlideFrame } = this.props;
    const { isPreVersion } = _isSlideFrame ? this.props.params : this.props.location.query;
    return (
      <SlideDocument
        loading={loading}
        className='slide-request-detail'
        fieldsParams={{
          annotateDisabled: true,
          showEdit: true,
          onClickEdit: this.onClickEditFields,
        }}
        left={
          <div className="slide-application-header">
            <ApplicationHeader isEdit quotaObj={quotaObj} isPreVersion={isPreVersion} />
          </div>
        }
        right={
          <div className='slide-request-detail-right'>
            <If value={info.applicationOID}>
              <Tabs
                activeKey={activeTab}
                className="right-tabs"
                onChange={activeTab => this.setState({ activeTab })}
              >
                <TabPane tab={messages('request-1.key271')/*行程明细*/} key='itinerary'>
                  <ItineraryBlock />
                </TabPane>
                {budgetExplainNumber > 0 && (
                  <TabPane tab={messages('request-1.key23')/*预算执行信息*/} key="budgetExplain">
                    <div className="budget-explain-block">
                      <BudgetExplain documentType="EXP_REQUISITION" documentId={info.applicationOID}/>
                    </div>
                  </TabPane>
                )}
                {info.approvalHistorys && info.approvalHistorys.length && (
                  <TabPane tab={messages('request-1.key24')/*审批历史*/} key="approvals">
                    <ApproveHistory
                      approvalChains={info.approvalChains}
                      isShowReply={false}
                      businessCode={info.businessCode}
                      approvalHistory={info.approvalHistorys}
                      applicantInfo={info.applicant || {}}
                    />
                  </TabPane>
                )}
              </Tabs>
            </If>
          </div>
        }
        bar={<BottomBlockEdit quotaObj={quotaObj}/>}
      />
    )
  }
}

RequestEdit.childContextTypes = {
  applicant: PropTypes.object,
  creditScore: PropTypes.object,
  jobInfo: PropTypes.object,
  form: PropTypes.object,
  info: PropTypes.object,
  close: PropTypes.func,
  refreshInfo: PropTypes.func,
  thirdPartyInfo: PropTypes.object,
  refreshQuotaObj: PropTypes.func,
};

RequestEdit.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    loginUser: state.login.loginUser
  }
}

export default connect(mapStateToProps)(RequestEdit)
